from django.shortcuts import redirect
from models_goods.oo import *


# 根据保管人查询
""" 
def search(request):
        user_name_list = AllUserName().get_info()
        print(user_name_list)

        # 获取search.html中的数据库内的查询的名字
        man = request.GET.get('bbb')

        try:
            res = StockControl.objects.filter(user__name=man)
        except:
            context = {
                # "user_name_list": user_name_list,
                "mes": '此人没有保管任何东西',
            }
            return render(request, 'asset_search/search.html', context)
        else:
            context = {
                # "user_name_list": user_name_list,
                "storeman": res,
            }
            return render(request, 'asset_search/search.html', context)
"""


# 根据保管人查询
def search(request):
    user_name_list = AllUserName().get_info()

    if request.method == 'GET':
        context = {'user_name_list': user_name_list}
        return render(request, 'asset_search/search.html', context)

    elif request.method == 'POST':
        # 获取search.html中的数据库内的查询的名字
        list_data = StockControl.objects.filter(user=request.POST['asset']).values_list(
                'goods__name', 'room__tower__name', 'room__floor__name', 'room__room', 
                'user__name', 'number', 'unit', 'id')

        # 获取search.html中的asset数据，即资产转移保管人的id（注:此为字符串类型）
        asset = request.POST.get('asset')
        asset = int(asset)
        # 下拉菜单失效
        # context = {"list_data": list_data, }
        # 下拉菜单完好
        context = {'user_name_list': user_name_list, 'asset': asset}
        context.update({"list_data": list_data, })
        context['title'] = '根据保管人:<{}>进行查询'.format(StockControl.objects.filter(
            user_id=request.POST['asset'])[0].user.name)
        
        return render(request, 'asset_search/search.html', context)


# 修改资产数量和单位
def amend(request, uid):
    if request.method == 'GET':
        u = StockControl.objects.get(pk=uid)
        context = {'uid': u}
        return render(request, 'asset_search/amend.html', context)
    elif request.method == "POST":
        goods = request.POST.get("goods")
        lou = request.POST.get('lou')
        ceng = request.POST.get('ceng')
        shi = request.POST.get('shi')
        number = request.POST.get("number")
        unit = request.POST.get("unit")

        u = StockControl.objects.get(pk=uid)
        g = Goods.objects.get(pk=u.goods_id)
        r = Rooms.objects.get(pk=u.room_id)
        t = Tower.objects.get(pk=u.room.tower_id)
        f = Floor.objects.get(pk=u.room.floor_id)
        g.name = goods
        t.name = lou
        f.name = ceng
        r.room = shi
        u.number = number
        u.unit = unit
        u.save()
        g.save()
        r.save()
        t.save()
        f.save()
        return redirect('index:index')






